//TODO: Optimize directions with waypoints (maybe)

// Innitial map values
var map;
var directionsService;
var markers = [];
var renderers = [];

window.onload = function() {
	initialize();
	
	// Add clickevent to create button
	var btnCreate = document.getElementById('btnCreate');
	btnCreate.addEventListener('click', saveRoute, false);
}

function initialize() {
	// Set initial center position
	var latlng = new google.maps.LatLng(50.979865,4.081088);
	
	directionsService = new google.maps.DirectionsService();
	
	map = new google.maps.Map(document.getElementById("map_canvas"), {
		zoom: 15,
		center: latlng,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	});
	
	polyline = new google.maps.Polyline({
		map: map
	});

	// Add marker on click
	google.maps.event.addListener(map, 'click', function(event) {
		addMarker(event.latLng);
	});

}

function addMarker(position) {
	
	var request = {
		origin: position,
		destination: position,
		travelMode: google.maps.DirectionsTravelMode.WALKING
	};
		
	// Snap marker to road by calculating route to self
	directionsService.route(request, function(response, status) {
		var marker = new google.maps.Marker({
			position: response.routes[0].legs[0].start_location, 
			map: map,
			draggable: true
		});
		
		// Add marker to array
		markers.push(marker);
		
		// Calculate route when more than 1 marker has been added
		if(markers.length > 1) {
			updateRoute();
		}
		
		// Drag marker
		google.maps.event.addListener(marker, 'dragend', function(e) {
			snapMarker(marker); // Snap marker back to road after drag
			updateRoute(); // Update route after drag
		});
	});
}

// Snap marker to nearest road
function snapMarker(marker) {
	var request = {
		origin: marker.getPosition(),
		destination: marker.getPosition(),
		travelMode: google.maps.DirectionsTravelMode.WALKING
	};
	
	directionsService.route(request, function(response, status) {
		marker.setPosition(response.routes[0].legs[0].start_location);
	});
}

function updateRoute() {
	//alert('update');
	
	for(var j = 0; j < renderers.length; j++) {
		renderers[j].setMap(null);
	}
	
	for(var i = 1; i < markers.length; i++) {
		var origin = markers[i - 1].getPosition();
		var destination = markers[i].getPosition();
		
		var request = {
			origin: origin,
			destination: destination,
			travelMode: google.maps.DirectionsTravelMode.WALKING
		}
		//alert(request.origin + '->' + request.destination);
		directionsService.route(request, function(response, status) {
			if (status == google.maps.DirectionsStatus.OK) {
				//alert(':)');
				drawRoute(response);
			} else if (status == google.maps.DirectionsStatus.ZERO_RESULTS) {
				alert("Could not find a route between these points");
			} else {
				alert("Directions request failed");
			}
		});
	}
}

function drawRoute(response) {
	//alert('draw');
	
	//renderers.clear();
	
	var directionsRenderer = new google.maps.DirectionsRenderer({
		preserveViewport: true,
		map: map,
		suppressMarkers: true
	});
	
	renderers.push(directionsRenderer);
	
	directionsRenderer.setDirections(response);
}

// Create page interaction

function saveRoute() {
	if(markers.length < 2) {
		alert('You need to create a route first before submitting!');
	}
	else {
		$.get("./core/includes/config.php", function(data){
			alert("Data Loaded: " + data);
		});
	}
	
	
	return false; // Shouldn't submit (yet)
}